<template>
  <div class="order-view">
    <el-dialog
      :title=title
      :visible.sync="addShow"
      width="60%"
      v-if="addShow"
      :before-close="handleClose"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <div>
        <el-form ref="form" inline :model="form" label-width="150px" label-position="left">
          <el-button
            v-if="!isUpd"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="selBuyOrder"
          >选择采购订单
          </el-button>
          <el-button
            v-if="!isUpd"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="selSaleBack"
          >选择销售退货单
          </el-button>
          <el-button
            v-if="!isUpd"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="selStockOut"
          >选择调拨出库单
          </el-button>
          <br>
          <el-form-item label="入库单编号" prop="stockInCode">
            <el-input v-model="form.stockInCode" disabled placeholder="请输入入库单编号"/>
          </el-form-item>
          <el-form-item label="订单编号" prop="orderCode">
            <el-input v-model="form.orderCode" placeholder="请选择入库订单" disabled/>
          </el-form-item>
          <el-form-item label="入库类型" prop="typeName">
            <el-input disabled v-model="form.typeName" placeholder="入库类型"/>
          </el-form-item>
          <el-form-item label="合格数量" prop="passNum">
            <el-input disabled v-model="form.passNum" placeholder="合格数量"/>
          </el-form-item>
          <el-form-item label="不合格数量" prop="noPassNum">
            <el-input disabled v-model="form.noPassNum" placeholder="不合格数量"/>
          </el-form-item>
          <el-form-item label="总数量" prop="totalNum">
            <el-input disabled v-model="form.totalNum" placeholder="总数量"/>
          </el-form-item>
          <el-form-item label="合格率" prop="passRate">
            <el-input disabled v-model="form.passRate" placeholder="合格率"/>
          </el-form-item>
          <el-form-item label="合格价" prop="passCost">
            <el-input disabled v-model="form.passCost" placeholder="合格价"/>
          </el-form-item>
          <el-form-item label="总价" prop="cost">
            <el-input disabled v-model="form.cost" placeholder="总价"/>
          </el-form-item>
          <!--          <el-form-item label="仓库" prop="houseName">-->
          <!--            <el-input v-model="form.houseName" placeholder="仓库" @focus="selHouse"/>-->
          <!--          </el-form-item>-->
        </el-form>
      </div>
      <!--        detail表格-->
      <el-table :data="stockInDetailList" style="width: 100%">
<!--        <el-table-column label="序号" align="center">-->
<!--          <template slot-scope="scope">-->
<!--            {{ scope.$index + 1 }}-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="商品名称" align="center" prop="proName"/>
        <el-table-column label="仓库名称" width="120" align="center" prop="houseName">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.houseName"
              @focus="selHouse(scope.row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="入库数量" align="center" prop="num"/>
        <el-table-column label="不合格数量" align="center" prop="noPassNum">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.noPassNum"
              @change="changeNoPassNum(scope.row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="总数量" align="center" prop="totalNum">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.totalNum"
              @change="changeTotalNum(scope.row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="合格率" align="center" prop="passRate"/>
        <el-table-column label="商品价格" align="center" prop="cost"/>
        <el-table-column label="合格价格" align="center" prop="passCost"/>
        <el-table-column label="总价格" align="center" prop="costAll"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row.proCode)"
              v-hasPermi="['xiaoshou:saleBackRequest:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="选择 销售退货单"
                 :visible.sync="showSelSaleBack"
                 width="60%"
                 :before-close="handleClose"
                 :modal-append-to-body="false"
                 :append-to-body="true">
        <el-table :data="saleBackList">
<!--          <el-table-column label="序号" align="center">-->
<!--            <template slot-scope="scope">-->
<!--              {{ scope.$index + 1 }}-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column label="销售退货单编号" align="center" prop="saleBackCode">
            <template slot-scope="scope">
              <el-button type="text" @click="confirmSaleBack(scope.row)">{{
                  scope.row.saleBackCode
                }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="销售退货申请单编号" align="center" prop="saleBackRequestCode"/>
          <el-table-column label="总价" align="center" prop="total"/>
          <el-table-column label="创建人" align="center" prop="createBy"/>
          <el-table-column label="创建时间" align="center" prop="createDate"/>
        </el-table>
        <pagination
          v-show="totalSize>0"
          :total="totalSize"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="selSaleBack"
        />
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <el-dialog title="选择 采购订单"
                 :visible.sync="showSelBuyOrder"
                 width="60%"
                 :before-close="handleClose"
                 :modal-append-to-body="false"
                 :append-to-body="true">
        <el-table :data="buyOrderList">
<!--          <el-table-column label="序号" align="center">-->
<!--            <template slot-scope="scope">-->
<!--              {{ scope.$index + 1 }}-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column label="采购订单编号" align="center" prop="code">
            <template slot-scope="scope">
              <el-button type="text" @click="confirmBuyOrder(scope.row)">{{
                  scope.row.code
                }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="源单据号" align="center" prop="sourceCode"/>
<!--          <el-table-column label="总价" align="center" prop="total"/>-->
          <el-table-column label="创建人" align="center" prop="createBy"/>
          <el-table-column label="创建时间" align="center" prop="createTime"/>
        </el-table>
        <pagination
          v-show="totalSize>0"
          :total="totalSize"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="selBuyOrder"
        />
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <el-dialog title="选择 调拨出库单"
                 :visible.sync="showSelStockOut"
                 width="60%"
                 :before-close="handleClose"
                 :modal-append-to-body="false"
                 :append-to-body="true">
        <el-table :data="stockOutList">
          <!--          <el-table-column label="序号" align="center">-->
          <!--            <template slot-scope="scope">-->
          <!--              {{ scope.$index + 1 }}-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column label="调拨出库单编号" align="center" prop="code">
            <template slot-scope="scope">
              <el-button type="text" @click="confirmStockOut(scope.row)">{{
                  scope.row.stockOutCode
                }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="源单据号" align="center" prop="orderCode"/>
          <!--          <el-table-column label="总价" align="center" prop="total"/>-->
          <el-table-column label="创建人" align="center" prop="createBy"/>
          <el-table-column label="创建时间" align="center" prop="createDate"/>
        </el-table>
        <pagination
          v-show="totalSize>0"
          :total="totalSize"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="selBuyOrder"
        />
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <el-dialog title="选择 仓库"
                 :visible.sync="showSelHouse"
                 width="60%"
                 :before-close="handleClose"
                 :modal-append-to-body="false"
                 :append-to-body="true">
        <el-table :data="houseList">
<!--          <el-table-column label="序号" align="center">-->
<!--            <template slot-scope="scope">-->
<!--              {{ scope.$index + 1 }}-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column label="仓库编号" align="center" prop="houseCode">
            <template slot-scope="scope">
              <el-button type="text" @click="confirmHouse(scope.row)">{{
                  scope.row.houseCode
                }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="仓库名称" align="center" prop="houseName"/>
          <el-table-column label="创建人" align="center" prop="createBy"/>
          <el-table-column label="创建时间" align="center" prop="createDate"/>
        </el-table>
        <pagination
          v-show="totalSize>0"
          :total="totalSize"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="selHouse"
        />
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelSelHouse">取 消</el-button>
        </div>
      </el-dialog>

      <span slot="footer" class="dialog-footer">
        <el-button @click="submitForm">提 交</el-button>
        <el-button @click="closeAdd">关 闭</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import request from '@/utils/request';

export default {
  name: "AddStockIn",
  props: ["updData"],
  data() {
    return {
      buyOrderList:[],
      showSelHouse: false,
      title: "添加 入库单",
      dialogVisible: false,
      addShow: false,
      isUpd: false,
      showSelBuyOrder:false,
      showSelSaleBack: false,
      showSelStockOut:false,
      stockOut:{},
      stockOutList:[],
      stockOutDetailList:[],
      saleBackRequest: {},
      saleBackRequestList: [],
      stockIn: {},
      stockInDetailList: [],
      saleBackList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      form: {
        cost: 0
      },
      totalDetail: 0,
      totalSize: 0,
      totalPrice: 0,
      houseList: [],
      selGoodsId: 0,
      allSelHouse: false,
    };
  },
  watch: {
    totalPrice() {
      this.form.total = this.totalPrice;
    },
    updData(newValue) {
      this.form = newValue;
      this.getStockInDetailList();
    }
  },
  methods: {
    confirmHouse(row) {
      this.form.houseName = row.houseName;
      this.stockInDetailList.forEach(item => {
        if (item.goodsId == this.selGoodsId) {
          item.houseId = row.id;
          item.houseName = row.houseName;
          console.log("item", item)
        }
      })
      this.queryParams.pageNum = 1;
      this.showSelHouse = false;
    },
    cancelSelHouse() {
      this.showSelHouse = false;
      this.queryParams.pageNum = 1;
    },
    selHouse(row) {
      request({
        url: "/store/warehouseInfo/list",
        params: this.queryParams,
        method: "get"
      }).then(res => {
        this.houseList = res.rows;
        this.selGoodsId = row.goodsId;
        this.showSelHouse = true;
      })
    },
    handleDelete(proCode) {
      // 找到要删除的对象的索引
      const index = this.stockInDetailList.findIndex(item => item.proCode === proCode);
      if (index !== -1) {
        // 使用 splice 删除对象
        this.stockInDetailList.splice(index, 1);
        this.$notify({
          title: '成功',
          message: '已成功删除商品',
          type: 'success',
        });
      } else {
        this.$notify({
          title: '错误',
          message: '未找到要删除的商品',
          type: 'error',
        });
      }
      this.calData();
    },
    reset() {
      this.resetForm("form");
      this.saleBack = {};
      this.saleBackRequestList = [];
      this.buyOrder = {};
    },
    //修改总数量
    changeTotalNum(row) {
      if (isNaN(row.totalNum) || row.totalNum <= 0) {
        this.$notify({
          title: '警告',
          message: '请输入正整数',
          type: 'warning',
        });
        row.totalNum = row.inputNum; // 恢复为num
        return;
      }
      if (row.totalNum > row.inputNum) {
        this.$notify({
          title: '警告',
          message: `输入的数量不能大于` + row.inputNum,
          type: 'warning',
        });
        row.totalNum = row.inputNum; // 恢复为num
        return;
      }
      row.noPassNum = 0;
      this.calData();
    },
    //修改不合格数量
    changeNoPassNum(row) {
      if (isNaN(row.noPassNum) || row.noPassNum < 0) {
        this.$notify({
          title: '警告',
          message: '请输入正整数',
          type: 'warning',
        });
        row.noPassNum = 0; // 恢复为0
        return;
      }
      if (row.noPassNum > row.totalNum) {
        this.$notify({
          title: '警告',
          message: `输入的数量不能大于` + row.totalNum,
          type: 'warning',
        });
        row.noPassNum = 0; // 恢复为0
        return;
      }
      this.calData();
    },
    showAdd() {
      this.form = {
        cost: 0
      };
      this.stockInDetailList = [];
      this.title = "添加 入库单";
      this.form.stockInCode = "";
      this.form.stockInCode = "RK" + new Date().getTime();
      this.addShow = true;
    },
    showUpd() {
      this.title = "修改 入库单";
      this.isUpd = true;
      this.addShow = true;
    },
    getStockInDetailList() {
      this.stockInDetailList = [];
      request({
        url: "/store/stockInDetail/list",
        params: {
          stockInId: this.form.id
        },
        method: "get"
      }).then(res => {
        this.stockInDetailList = res.rows;
        this.stockInDetailList.forEach(item => {
          item.inputNum = item.totalNum;
        })
        this.addShow = true;
      });
    },
    closeAdd() {
      this.reset();
      this.isUpd = false;
      this.addShow = false;
    },
    confirmBuyOrder(row){
      this.buyOrder = row;
      request({
        url: "/caigou/buyOrderGoods/useList",
        params: {
          buyOrderCode: row.code
        },
        method: "get"
      }).then(res => {
        let buyOrderGoodsList = res.rows;
        if (!(buyOrderGoodsList.length > 0)) {
          this.$notify({
            title: '警告',
            message: '该订单已无可入库商品',
            type: 'warning',
          });
        } else {
          this.form.typeName = "采购入库";
          this.form.inventoryType = 1;
          this.stockInDetailList = [];
          buyOrderGoodsList.forEach(item => {
            const detail = {
              goodsId: item.goodsId,
              houseId: 0,
              houseName: "",
              proName: item.proName,
              totalNum: item.purchaseQuantity,
              inputNum: item.purchaseQuantity,
              cost: item.price,
              num: item.purchaseQuantity,
              noPassNum: 0,
              passRate: 1,
              passCost: item.price * item.purchaseQuantity,
              costAll: item.price * item.purchaseQuantity,
              createBy: this.$store.getters.name
            }
            this.stockInDetailList.push(detail);
          });
          this.form.orderCode = row.code;
          this.calData();
        // this.saleBackDetailList = res.rows;
        }
        this.showSelBuyOrder = false;
      });
    },
    confirmSaleBack(row) {
      this.saleBack = row;
      //获取退货详情列表给到入库详情
      request({
        url: "/xiaoshou/saleBackDetail/useList",
        params: {
          saleBackCode: row.saleBackCode
        },
        method: "post"
      }).then(res => {
        this.form.typeName = "销售退货入库";
        this.form.inventoryType = 4;
        this.saleBackDetailList = res.rows;
        if (!(this.saleBackDetailList.length > 0)) {
          this.$notify({
            title: '警告',
            message: '该订单已无可入库商品',
            type: 'warning',
          });
        } else {
          this.stockInDetailList = [];
          this.saleBackDetailList.forEach(item => {
            const detail = {
              goodsId: item.goodsId,
              houseId: 0,
              houseName: "",
              proName: item.proName,
              totalNum: item.proNum,
              inputNum: item.proNum,
              cost: item.price,
              num: item.proNum,
              noPassNum: 0,
              passRate: 1,
              passCost: item.price * item.proNum,
              costAll: item.price * item.proNum,
              createBy: this.$store.getters.name
            }
            this.stockInDetailList.push(detail);
          });
          this.form.orderCode = row.saleBackCode;
          this.calData();
        }
        this.showSelSaleBack = false;
      });
    },
    confirmStockOut(row){
      this.stockOut = row;
      //获取出库详情列表给到入库详情
      request({
        url: "/store/stockOutDetail/getOutDetailByOutId/"+row.id,
        method: "get"
      }).then(res => {
        this.stockOutDetailList = res.data;
        if (!(this.stockOutDetailList.length > 0)) {
          this.$notify({
            title: '警告',
            message: '该出库单已无可入库商品',
            type: 'warning',
          });
        } else {
          this.form.typeName = "调拨入库";
          this.form.inventoryType = 6;
          this.stockInDetailList = [];
          this.stockOutDetailList.forEach(item => {
            const detail = {
              goodsId: item.goodsId,
              houseId: 0,
              houseName: "",
              proName: item.proName,
              totalNum: item.stockOutNumber,
              inputNum: item.stockOutNumber,
              cost: item.cost,
              num: item.stockOutNumber,
              noPassNum: 0,
              passRate: 1,
              passCost: item.cost * item.stockOutNumber,
              costAll: item.cost * item.stockOutNumber,
              createBy: this.$store.getters.name
            }
            this.stockInDetailList.push(detail);
          });
          this.form.orderCode = row.stockOutCode;
          this.calData();
        }
        this.showSelStockOut = false;
      });
    },
    //计算数据的方法
    calData() {
      let cost = 0;
      let passNum = 0;
      let totalNum = 0;
      let passCost = 0;
      this.stockInDetailList.forEach(item => {
        item.num = item.totalNum - item.noPassNum;
        item.passCost = (item.num * item.cost).toFixed(2);
        item.passRate = (item.num / item.totalNum).toFixed(4);
        item.costAll = (item.totalNum * item.cost).toFixed(2);
        cost = (parseFloat(cost) + parseFloat(item.costAll)).toFixed(2);
        passNum = parseFloat(passNum) + parseFloat(item.num);
        totalNum = parseFloat(totalNum) + parseFloat(item.totalNum);
        passCost = (parseFloat(passCost) + parseFloat(item.passCost)).toFixed(2);
      });
      this.form.cost = cost;
      this.form.passNum = passNum;
      this.form.totalNum = totalNum;
      this.form.passCost = passCost;
      this.form.passRate = (this.form.passNum / this.form.totalNum).toFixed(4);
      this.form.noPassNum = this.form.totalNum - this.form.passNum;
      this.form = {
        ...this.form, cost, passNum, totalNum, passCost, passRate: (this.form.passNum / this.form.totalNum).toFixed(4)
        , noPassNum: this.form.totalNum - this.form.passNum
      }
    },
    handleClose(done) {
      done();
    },
    //弹出已确认的采购订单列表
    selBuyOrder() {
      // this.queryParams.status = 1;
      request({
        url: "/caigou/buyOrder/list",
        method: "get",
        params: this.queryParams
      }).then(res => {
        if (res.code == 200) {
          this.buyOrderList = res.rows;
          this.totalSize = res.total;
          this.showSelBuyOrder = true;
        }
      });
    },
    //弹出已确认的调拨出库单列表
    selStockOut() {
      this.queryParams.stockStatus = 2;
      this.queryParams.inventoryTypeId=5;
      request({
        url: "/store/stockOut/getStockTranList",
        method: "get",
        params: this.queryParams
      }).then(res => {
        if (res.code == 200) {
          this.stockOutList = res.rows;
          this.totalSize = res.total;
          this.showSelStockOut = true;
        }
      });
    },
    //弹出已确认的销售退货单列表
    selSaleBack() {
      this.queryParams.status = 1;
      request({
        url: "/xiaoshou/saleBack/getUseList",
        method: "get",
        params: this.queryParams
      }).then(res => {
        if (res.code == 200) {
          this.saleBackList = res.rows;
          this.totalSize = res.total;
          this.showSelSaleBack = true;
        }
      });
    },
    check() {
      if (this.form.stockInCode == null || this.form.stockInCode == '') {
        this.$notify({
          title: "警告",
          message: "入库单编号不能为空！",
          type: "warning",
        })
        return false;
      }
      if (this.form.orderCode == null || this.form.orderCode == '') {
        this.$notify({
          title: "警告",
          message: "订单编号不能为空！",
          type: "warning",
        })
        return false;
      }
      if (!this.form.totalNum > 0) {
        this.$notify({
          title: "警告",
          message: "总数量必须大于0！",
          type: "warning",
        })
        return false;
      }
      this.stockInDetailList.some(item => {
        console.log("list", this.stockInDetailList)
        if (item.houseId > 0) {
          this.allSelHouse = true;
          return false;
        } else {
          this.allSelHouse = false;
          return true;
        }
      })
      return true;
    },
    submitForm() {
      if (!this.check()) {
        return;
      }
      if (!this.allSelHouse) {
        this.$notify({
          title: "警告",
          message: "请选择仓库！",
          type: "warning",
        })
        return;
      }
      this.form.houseId = 1;
      this.form.createBy = this.$store.getters.name;
      this.form.updateBy = this.$store.getters.name;
      this.stockInDetailList.forEach(item => {
        item.createBy = this.$store.getters.name
      })
      this.form.stockInDetails = this.stockInDetailList;
      if (!this.isUpd) {
        request({
          url: "/store/stockIn/addStockIn",
          data: this.form,
          method: "post",
        }).then(res => {
          if (res.code == 200) {
            this.$modal.msgSuccess("新增成功");
            this.$emit("updList");
            this.addShow = false;
            this.reset();
          } else {
            this.$modal.msgError(res.msg);
          }
        }).catch(e => {
          this.$modal.msgError(e);
        })
      } else {
        this.form.stockInDetails = this.stockInDetailList;
        this.form.modify = this.$store.getters.name;
        request({
          url: "/store/stockIn/updStockIn",
          data: this.form,
          method: "post",
        }).then(res => {
          if (res.code == 200) {
            this.$modal.msgSuccess("修改成功");
            this.$emit("updList");
            this.addShow = false;
            this.reset();
          } else {
            this.$modal.msgError(res.msg);
          }
        }).catch(e => {
          this.$modal.msgError(e);
        })
      }
    },
    cancel() {
      this.showSelBuyOrder = false;
      this.showSelSaleBack = false;
      this.showSelStockOut = false;
      this.queryParams.pageNum = 1;
    }
  },
};
</script>
